﻿using System;

namespace Microsoft.Coding4Fun.TweetCraft.Wow
{
    public class SavedVariablesChannelFactory : ISavedVariablesChannelFactory
    {
        private readonly IWorldOfWarcraft worldOfWarcraft;

        /// <summary>
        /// Initializes a new instance of the <see cref="SavedVariablesChannelFactory"/> class.
        /// </summary>
        /// <param name="worldOfWarcraft">The world of warcraft.</param>
        public SavedVariablesChannelFactory(IWorldOfWarcraft worldOfWarcraft)
        {
            if (worldOfWarcraft == null)
                throw new ArgumentNullException("worldOfWarcraft");

            this.worldOfWarcraft = worldOfWarcraft;
        }

        /// <summary>
        /// Gets or sets the name of the account.
        /// </summary>
        public string AccountName { get; set; }

        /// <summary>
        /// Gets or sets the name of the addon.
        /// </summary>
        public string AddOnName { get; set; }

        /// <summary>
        /// Returns a value indicating whether the channel factory can create a channel.
        /// </summary>
        /// <returns></returns>
        public bool CanCreateChannel()
        {
            return !String.IsNullOrEmpty(this.AccountName) &&
                   !String.IsNullOrEmpty(this.AddOnName);
        }

        /// <summary>
        /// Create an <see cref="IValueChannel"/>.
        /// </summary>
        /// <returns>
        /// An instance of a class that implements <see cref="IValueChannel"/>.
        /// </returns>
        IValueChannel IValueChannelFactory.CreateChannel()
        {
            return CreateChannel();
        }

        /// <summary>
        /// Create an <see cref="ISavedVariablesChannel"/>.
        /// </summary>
        /// <returns>An instance of a class that implements <see cref="ISavedVariablesChannel"/>.</returns>
        public ISavedVariablesChannel CreateChannel()
        {
            if (!this.CanCreateChannel())
                throw new InvalidOperationException(Strings.CannotCreateChannelRequiredPropertiesNotSet);

            string savedVariablesPath = worldOfWarcraft.GetSavedVariablesPath(this.AccountName, this.AddOnName);

            using (TraceScope trace = TraceScope.Information("Creating SavedVariables channel using file {0}...", savedVariablesPath))
            {
                var channel = new SavedVariablesChannel(savedVariablesPath)
                              {
                                  AutoFlush = true
                              };

                trace.Complete("SavedVariables channel created.");

                return channel;
            }
        }
    }
}